import plugin from '../../../lib/plugins/plugin.js'
import fetch from 'node-fetch'
import fs from 'fs'
import moment from 'moment'
import { Config } from '../components/index.js'
import { common } from '../model/index.js'
const path = process.cwd() + '/plugins/xiaoyue-plugin/resources/xyplus/'
let usedvideo
export class XyPlus extends plugin {
  constructor () {
    super({
      name: '小月plus',
      dsc: '神秘指令',
      event: 'message',
      priority: 1568,
      rule: [
        {
          reg: '^#?(xy|小月)plus$',
          fnc: 'xyplus'
        },
        {
          reg: '^#?录入|收录$',
          fnc: 'add'
        },
        {
          reg: 'https(.*)(douyin|v.kuaishou)(.*)$',
          fnc: 'jiexi'
        }
      ]
    })
  }

  async xyplus (e) {
    let pluspath = await getPath()
    let videoList = JSON.parse(fs.readFileSync(`${pluspath}`, 'utf8'))
    if (!videoList.length) {
      e.reply('还没有收录视频哦~')
      return true
    }
    let currentTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    let lastTime = await redis.get(`Yxy:xy-plugin_plus:${e.group_id}`)
    if (lastTime && !e.isMaster) {
      let seconds = moment(lastTime).diff(moment(currentTime), 'seconds')
      e.reply(`cd中，请等待${seconds}秒后再使用`)
      return true
    }
    usedvideo = videoList
    let num = Math.round(Math.random() * (usedvideo.length - 1))
    let res = await e.reply(usedvideo[num])
    if (!res) return e.reply('视频发送失败，可能被风控')
    let config = await Config.xyss
    if (config.pluscd > 0) {
      let endTime = moment(Date.now()).add(config.pluscd, 'seconds').format('YYYY-MM-DD HH:mm:ss')
      await redis.set(`Yxy:xy-plugin_plus:${e.group_id}`, endTime, {
        EX: config.pluscd
      })
    }
    usedvideo.splice(num, 1)
  }

  // 录入视频(直接对视频回复“收录”)=================
  async add (e) {
    if (!e.isMaster) return false
    if (!e.source) return false
    // 获取引用的视频
    let video = await this.getReplyVideo(e)
    if (!video) return false
    this.addvideo(video)
    return true
  }


  // 解析
  async jiexi (e) {
    let config = await Config.xyss
    if (!config.jiexi) return false
    e.reply('正在解析中，请稍等片刻~')
    try {
      let url = /douyin/.test(e.msg) ? await this.dyjxReq() : await this.ksjxReq()
      let response = await fetch(url)
      let buff = await response.arrayBuffer()
      fs.writeFileSync(`${path}xyqwq.mp4`, Buffer.from(buff), 'binary')
      e.reply(segment.video(`file:///${path}xyqwq.mp4`))
    } catch (err) {
      logger.error(err)
      e.reply('解析失败')
    }
  }

  async dyGetMid () {
    let url = this.getHttpUrl()
    let origReg = /https?:\/\/www.douyin.com\/video\/(.*)/
    let mid = url.match(origReg)?.[1]
    if (mid) {
      this.mid = mid
      return
    }
    mid = new URL(url).searchParams.get('modal_id')
    if (mid) {
      this.mid = mid
      return
    }
    let res = await fetch(url)
    this.mid = res.url.match(/video\/(.*?)\//)?.[1]
  }

  async dyjxReq () {
    await this.dyGetMid()
    if (!this.mid) throw Error('解析失败')
    let url = 'https://www.douyin.com/video/' + this.mid
    console.log(url)
    let gh = await fetch(url, {
      method: 'GET',
      headers: {
        cookie: 'douyin.com; __ac_referer=https://www.douyin.com/video/7200695840900468008?previous_page=app_code_link; ttwid=1|j0PqIlrsmT-PHeVL26MUtN9yWhDtKz30FgIuxpGtk80|1674043522|ae7ca62b2f5b11ae675d1dbaa91768445c433af4faf7c61f1f7c5f52eece4bf9; passport_csrf_token=aaa188ac0b7b481a1380949b67d3d703; passport_csrf_token_default=aaa188ac0b7b481a1380949b67d3d703; s_v_web_id=verify_lfl7886x_rxeSUCen_4cnm_48bF_9NrH_hxQbP70AdImW; download_guide="3/20230324"; _tea_utm_cache_2018=undefined; douyin.com; VIDEO_FILTER_MEMO_SELECT={"expireTime":1680431163129,"type":1}; strategyABtestKey="1679854423.401"; SEARCH_RESULT_LIST_TYPE="single"; bd_ticket_guard_client_data=eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWNsaWVudC1jc3IiOiItLS0tLUJFR0lOIENFUlRJRklDQVRFIFJFUVVFU1QtLS0tLVxyXG5NSUlCRFRDQnRRSUJBREFuTVFzd0NRWURWUVFHRXdKRFR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N6VuntHZN1b1QGG6IMCub_VE=',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.51'
      }
    })
    gh = await gh.text()
    let vd = gh.match(/src%22%3A%22%2F%2Fv26(.*?)%22%7D%2C%7B%22/g)
    vd = `${vd}`
    let gg = vd.split(',')
    let hh = decodeURIComponent(gg[1])
    hh = hh.replace('src":"', 'https:').replace('"},{"', '')
    return hh
  }

  async getksId () {
    let url = this.getHttpUrl()
    let res = await fetch(url)
    this.ksId = res.url.match(/\/long-video\/(.*)\?/)?.[1]
  }

  getHttpUrl () {
    let httpReg = /(https?|http|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g
    return this.e.msg.match(httpReg)?.[0]
  }

  async ksjxReq () {
    await this.getksId()
    if (!this.ksId) throw Error('解析失败')
    let url = 'https://www.kuaishou.com/short-video/' + this.ksId
    let a = await
    fetch(url, {
      headers: {
        'Content-Type': 'application/json',
        cookie:
            'userId=1505388048; kpn=KUAISHOU_VISION; kuaishou.server.web_st=ChZrdWFpc2hvdS5zZXJ2ZXIud2ViLnN0EqABEyMOS47P8cIjPuL7rrQW-ajyIvkgh_zZ6Q2AoMFASbFgA9o544HKE4zYvgzQ9em8Ixn3dhHIZyfFiBsTVZY7plf70WmmJxnHMklAIfIApv7uNyMTdaWyNFoceuDQYpWj4NNMykkogHq8QSy5cie7lSaNkh-w-k5K-XX2MDh3R6yJRNaASZF2mCi-GwSjQe7Km9TeITGMtV735iJ3TnyBFRoS_47WhL3lHryRDUsr7Z0BqLaUIiCroxVcd5uCuCWDxmT8fu3nOdAOc5DzUealy45EKftNSCgFMAE; kuaishou.server.web_ph=f2d40c46fcb630d96326b5d939f15a895176',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0 Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.51'
      },
      method: 'GET'
    })
    a = await a.text()
    let b = a.match(/"photoH265Url":(.*?)vp/g)
    b = `${b}`
    return b.replace('"photoH265Url":', '').replace(/"/g, '').replace(/\\u002F/g, '/')
  }

  // 存视频==================================
  async addvideo (video) {
    let pluspath = await getPath()
    let videoList = JSON.parse(fs.readFileSync(`${pluspath}`, 'utf8'))
    // 查重
    for (let val of videoList) {
      if (val.md5 == video.md5) {
        this.e.reply('视频已存在')
        return true
      }
    }
    // 添加进videoList，写入文件
    videoList.push(video)
    fs.writeFileSync(`${pluspath}`, JSON.stringify(videoList, null, '\t'))
    this.e.reply('收录成功')
    return true
  }

  // 获取被引用的视频===============================
  async getReplyVideo (e) {
    let reply
    if (e.isGroup) {
      reply = (await e.group.getChatHistory(e.source.seq, 1)).pop()?.message
    } else {
      reply = (await e.friend.getChatHistory(e.source.time, 1)).pop()?.message
    }
    if (reply) {
      for (let val of reply) {
        if (val.type == 'video') {
          return val
        }
      }
    }
    return false
  }
}

async function getPath () {
  let config = await Config.xyss
  if (config.plususer) {
    let userpath = process.cwd() + '/plugins/xiaoyue-plugin/resources/xyplus/userplus.json'
    if (!fs.existsSync(userpath)) {
      fs.writeFileSync(userpath, JSON.stringify([]))
    }
    return userpath
  }
  let xypath = process.cwd() + '/plugins/xiaoyue-plugin/resources/xyplus/xyplus.json'
  return xypath
}
